<?php

namespace brand\logic;

use brand\build\Columns;
use brand\page\Page;
use brand\tools\Functions;
use think\facade\Db;

class PageCurd
{
    public static $curdName;

    public static $conditionWhere;
    public static $conditionSortField;
    public static $conditionSortOrder;
    public static $conditionLimit;

    public static $joinFields;
    public static $joinArray;

    /**
     * 构建搜索条件
     * @param $pk
     */
    public static function buildSelectCondition($pk)
    {

        [
            self::$conditionWhere,
            self::$conditionLimit,
            self::$conditionSortField,
            self::$conditionSortOrder,
        ] = BrandHelper::buildParams($pk,self::$curdName,Columns::getConfig());

    }

    /**
     * 构建join
     */
    public static function buildJoin()
    {
        $field = self::$curdName . ".*";
        $joins = [];
        $columns = Columns::getConfig();
        $table = self::$curdName;
        foreach ($columns as $name => $item) {

            if (isset($item['table']['relevancy']) && isset($item['table']['relevancy_key']) && ( !isset($item['form']['is_relevancy']) || !$item['form']['is_relevancy'] )){

                //关联表
//                $relevancy = '__BRAND_ADMIN__'.$item['table']['relevancy'];
                $relevancy = $item['table']['relevancy'];
                //关联主键
                $relevancy_key = $item['table']['relevancy_key'];

                //查询字段
                $relevancy_labels = $item['table']['relevancy_labels'] ?? [];
                foreach ($relevancy_labels as $relevancy_label) {
                    $field .= ','.$relevancy.'.'.$relevancy_label . ' as '. $item['table']['relevancy'] .'__BA__' . $relevancy_label;
                }

                $joins[] = [
                    'join' => $item['table']['relevancy'].' '.$relevancy,
                    'condition' => $relevancy.'.'.$relevancy_key . '=' . $table.'.'.$name,
                    'type'  =>  'left'
                ];
            }

        }

        self::$joinFields = $field;
        self::$joinArray = $joins;

    }

    /**
     * 格式化特殊字段
     * @param $list
     * @return mixed
     */
    public static function specialField($list)
    {
        //循环列表
        foreach ($list as $index => $table) {
            if (is_object($table)) $table = $table->toArray();
            //循环字段
            foreach ($table as $key=>$item) {
                $columns = Columns::getColumn($key);
                if (isset($columns['field']['data_type']) && Database::isFloatType($columns['field']['data_type'])){
                    $item = (float)$item;
                }
                if (Columns::getTableAction($key)){

                    $ClassName = Config::BRAND_NAMESPACE . Functions::toCamelCase(Columns::getTableAction($key));
                    $ClassObject = new $ClassName($columns,[]);
                    //验证字段
                    $item = $ClassObject->checkTableValue($key,$item);
                    $table[$key] = $item;
                }
                $special_type = $columns['special_type'] ?? 0;
                if ($special_type){
                    switch ($special_type){
                        case 'province':
                        case 'city':
                        case 'area':
                            $table[$key] = Db::name('area')->where('id',$table[$key])->value('name');
                            break;

                    }
                }
            }
            $list[$index] = $table;
        }
        return $list;
    }


    public static function buildStat($db = null, $isHtml = 0)
    {
        $statisticsConf = Page::getStatistics();
        if (!$statisticsConf) return null;
        $field = "";
        $table = BrandHelper::getTableNameByName(self::$curdName);
        foreach ($statisticsConf as $item) {
            if ($field) $field .= ',';
            $field .= "sum({$table}.{$item}) as $item";
        }
        if (!$db) $db = Db::name($table);
        $data = $db->alias($table)->where(PageCurd::$conditionWhere);
        foreach (PageCurd::$joinArray as $join) {
            $data = $data->join($join['join'],$join['condition'],$join['type']);
        }
        $stat = $data->field($field)->select()->first();
        if (is_object($stat)) $stat = $stat->toArray();

        $columns = Columns::getConfig();
        $statList = [];
        foreach ($stat as $key => $item) {
            $statList[] = [
                'field' => $key,
                'value' => $item ?: 0,
                'title' => $columns[$key]['title'] ?? "",
            ];
        }
        if (!$isHtml) return $statList;
        return self::buildStatHtml($statList);
    }

    public static function buildStatHtml($stat)
    {

        $html = "";
        if (!$stat) return  "";
        foreach ($stat as $item) {
            $html .= <<<HTML

            <div class="stat_list stat_field_{$item['field']}">
                <div class="stat_title">
                    {$item['title']}
                </div>
                <div class="stat_info">
                    {$item['value']}
                </div>
            </div>
            
HTML;
        }

        return $html;
    }

}